﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace winrar_keygen_csharp
{
    internal class Program
    {
        [DllImport("winrar-keygen-csharp.dll", EntryPoint = "generate_register_info", CallingConvention = CallingConvention.Cdecl)]
        public extern static IntPtr GenerateRegisterInfo(string UserName, string LicenseType);

        static void Main(string[] args)
        {
            Console.Write($"Input Your Name:");
            var username = Console.ReadLine();
            Console.Write($"Input Your License:");
            var license = Console.ReadLine();
            string registerLicense = string.Empty;
            var p = GenerateRegisterInfo(username.Trim(), license.Trim());
            registerLicense = Marshal.PtrToStringAnsi(p);
            if (string.IsNullOrEmpty(registerLicense))
            {
                Console.WriteLine($"License is null!");
                return;
            }
            var lines = registerLicense.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            using (FileStream fs = new FileStream("rarreg.key", FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                byte[] data = null;
                int i = 0;
                for (; i < lines.Length - 1; i++)
                {
                    data = Encoding.ASCII.GetBytes(lines[i] + Environment.NewLine);
                    fs.Write(data, 0, data.Length);
                }

                for (int j = 0;j < lines[i].Length; j+=54)
                {
                    data = Encoding.ASCII.GetBytes(lines[i].Substring(j, 54) + Environment.NewLine);
                    fs.Write(data, 0, data.Length);
                }
                fs.Flush();
            }
            Console.WriteLine($"Ok!");
            Console.ReadKey();
        }
    }
}
